
import gevent
from gevent import monkey
monkey.patch_all()

from bottle import static_file

from bottle import route, run

from bottle import template
import os,re,time
import random
import threading
import _thread
# @route('/hello')
# def hello():
#     # return "Hello World!"
#     return "./hello.html"



# @route('/static/<filename>')
# def send_static(filename):
#     return static_file(filename, root='./static')

# # @route('/static/<filename>')
# # def send_static(filename):
# #     # return static_file(filename, root='/static/')
# #     return "CCCCCCCCCCCCCCCC"

from bottle import get, post, request # or route

def check_login(username,password):
    if(username!="" and password!= ""):
        return 1
    else :
        return 0


@get('/login') # or @route('/login')
def login():
    return '''
        <form action="/login-submit" method="post">
            <p>
            Username: <input name="username" type="text" />
            </p>
            <p>
            Password: <input name="password" type="password" />
            </p>
            <p>
            info    : <input name="info" type="text" />
            <input value="Login" type="submit" />
            </p>
        </form>
    '''

@post('/login-submit') # or @route('/login', method='POST')
def do_login():
    username = request.forms.get('username')
    password = request.forms.get('password')
    print(username,password)
    if check_login(username, password):
        # return "<p>Your login information was correct.</p>"
        return static_file("hello.html", root='./static/')
    else:
        return "<p>Login failed.</p>"

@route('/showinfo/<user_code>')
def show(user_code):
    # test_count = random.randint(0,9)
    test_count=1
    try:
        mesg=open("./temp/"+user_code+"/.mesg")
        mesgLine=mesg.readline()
        mesg.close()
        print(mesgLine)
        if(mesgLine=="END\n"):
            print("in here"+mesgLine)
            test_count = 0
    except:
        pass
    try:
        files = open("./temp/"+user_code+"/"+user_code+".txt")
        text = files.readlines()   #check info
        files.close()
        #u_str = "["
        u_str=""
        u_count=0
        for line in text:
            #line=line[:-1]
            u_str+=line
            u_count+=1
        #u_str+="]"
        return template("gitLoad",text=u_str,en=test_count,row=u_count)
    except:
        return template("gitLoad",text="Wait...",en=test_count,row="5")

def shellThread(cmd):
    time.sleep(0.1)
    os.system(cmd)        



@post('/src-link') # or @route('/login', method='POST')
def send_static():
    test_count = random.randint(0,9)
    libre_git    = request.forms.get('libre_git')
    mcu_firmware = request.forms.get('mcu_firmware')
    info         = request.forms.get('info')

    gitLib_Name = re.search("/([^\/]*)\.git",libre_git).group(1)
    gitLib_Path ="./database/"+gitLib_Name

    if(os.path.exists(gitLib_Path)):
        print("dir  exists")
        #should be open a new thread
        t1=threading.Thread(target=shellThread,args=("sh ./shell/gitPull.sh "+gitLib_Name+" "+ libre_git,))
        t1.start()
        print("threading is open")
        #os.system("sh ./shell/gitPull.sh "+gitLib_Name+" "+ libre_git)
    else:
        print("dir don't exists")
#        os.system("sh ./shell/gitClone.sh "+gitLib_Name+" "+ libre_git+" "+mcu_firmware)
        t1=threading.Thread(target=shellThread,args=("sh ./shell/gitClone.sh "+gitLib_Name+" "+ libre_git+" "+mcu_firmware,))
        t1.start()
        # _thread.start_new_thread(os.system, ("sh ./shell/gitClone.sh "+gitLib_Name+" "+ libre_git+" "+mcu_firmware,)) 
        print("threading is open")
    print("will out")
    return template("submit",usercode=gitLib_Name) 

    # #1.判断用户文件夹是否存在
    # #2.判断对应git仓库是否存在
    #     #2.1 存在-git pull
    #     #2.2 不存在 git clone
    # #3.下载mcu固件
    # #4.合成固件
    # #5.加上info 打包
    # gitLib_Name = ""
    # gitLib_Path ="./database/"+gitLib_Name
    # # if(gitLib_Path.exists()):
    # #     #cd gitLib_Path
    # #     #git pull
    # #     #open a new thread
    # #     os.system("cd "+gitLib_Path)
    # #     output_info = os.popen('cd ./database').readlines()

    # # else:
    # #     os.system("cd "+gitLib_Path)
    # #     #cd gitLib_Path
    # #     #git clone


    # str1="git clone "+ libre_git
    # r = os.popen(str1)
    # info = r.readlines() #读取命令行的输出到一个list
    # print("i am run\r\n")
    # print(info)
    # for line in info: #按行遍历
    #     line = line.strip('\r\n')
    #     print(line)
    # r.close()
    # str2 = "you submit " + libre_git + mcu_firmware
    # # return template("gitLoad",text=test_count,en=test_count%2)
    # return ""


@get('/static/<filename>')
def send_static(filename):
    return static_file(filename, root='./static/',download=True)

@get('/download/<filename:path>')
def send_static(filename):
    return static_file(filename, root='.',download=True)
    # return static_file(filename, root='.')

@get('/view/<filename:path>')
def send_static(filename):
    # return static_file(filename, root='.',download=True)
    return static_file(filename, root='.')



# @route('/dir/<path:path>')
# def dirlist(path):
#     if(path=="root"):
#         s_path = "./static/"
#         path=""
#     else:
#         s_path = "./static/"+path+"/"
#     file_names = os.listdir(s_path)

#     text = "<html><body><h1>Welcome to merge</h1>"
#     print("in file scan")
#     for file in file_names:
#         print(file)
#         if os.path.isfile(s_path+file):
#             print("this is a file")
#             text=text+"<p><a href=\"/static/"+path+"/"+file+"\">"+file+"</a></p>"
#         elif os.path.isdir(s_path+file):
#             print("this is a dir")
#             text=text+"<p><a href=\"/dir/"+path+"/"+file+"\">"+file+"</a></p>"
#     text+="</body></html>"
#     return text


#@route('/files/<path>') 只支持 /files/aaa   不支持/files/   /files   /files/aaa/sffd   =>这一种可以加 path过滤

@route('/files/<path:path>')    #路由是dir   第一次进 /dir/database  如果是文件 连接为 /download/database/file => 下载 ./database/file   文件夹则 /dir/database/user_dir
def dirlist(path):
    s_path = "./"+path
    file_names = os.listdir(s_path)
    text = "<html><body><h1>Welcome to My database</h1>"
    print("in file scan")
    for file in file_names:
        print(file)
        if os.path.isfile(s_path+"/"+file):
            print("this is a file")
            text=text+"<p>"+file+" <a href=\"/view/"+path+"/"+file+"\">"+"view"+"</a>  <a href=\"/download/"+path+"/"+file+"\">"+"download"+"</a></p>"
        elif os.path.isdir(s_path+"/"+file):
            print("this is a dir")
            text=text+"<p><a href=\"/files/"+path+"/"+file+"\">"+file+"</a></p>"
    text+="</body></html>"
    return text

run(host='0.0.0.0', port=7777, debug=True,server='gevent')
# run(host='0.0.0.0', port=7777, debug=True)